package tsing.javase.quartz.job;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Date 2023/9/20 13:56
 */

@Service
public class VipNewAlarmService {
    public static final Logger logger = LoggerFactory.getLogger("vipnewalarm");
    @Autowired
    private VipAlarmDao mapper;
    // 定时任务调度器
    private static  Scheduler scheduler;
    static {
        try {
            scheduler =new StdSchedulerFactory().getScheduler();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    public List<AlarmRuleVO> queryVipAlarms(){
        return mapper.queryAlarmRules();
    }
    /**
     * 执行
     */
    public void excute(){
        // 查询表里的所有配置的告警任务
        logger.info("会员新告警查询配置的告警规则！！！！");

        try {
            List<AlarmRuleVO> alarmRuleVOS = queryVipAlarms();
            if(!CollectionUtils.isEmpty(alarmRuleVOS)){
                for (int i = 0; i <alarmRuleVOS.size() ; i++) {
                    logger.info("JOB配置："+ JSON.toJSONString(alarmRuleVOS.get(i)));
                    String fullClassName = alarmRuleVOS.get(i).getFullClassName();
                    Class<? extends Job>clazz;
                    if(StrUtil.isNotBlank(fullClassName)){
                        clazz = (Class<VipNewAlarmJob>) Class.forName(fullClassName);
                    }else{
                        clazz = VipNewAlarmJob.class;
                    }
                    String cronExpression = alarmRuleVOS.get(i).getCrons();
                    try {
                        String ruleConfId = alarmRuleVOS.get(i).getId();
                        // 保存可替换的参数
                        Map map = new HashMap<String,String>();
                        map.put("vipid",alarmRuleVOS.get(i).getVipid());
                        map.put("vippool",alarmRuleVOS.get(i).getVippool());
                        map.put("days",alarmRuleVOS.get(i).getDays());
                        // 创建JobDataMap
                        JobDataMap jobDataMap = new JobDataMap();
                        // 放入执行的SQl
                        jobDataMap.put("excelSql",alarmRuleVOS.get(i).getExcelSql());
                        // 放入配置的参数列表
                        jobDataMap.put("params",alarmRuleVOS.get(i).getParams());
                        // 放入可替换的参数
                        jobDataMap.put("replaceParams",map);
                        // 放入告警接收人
                        jobDataMap.put("phone",alarmRuleVOS.get(i).getPhone());
                        // 放入任务名称
                        jobDataMap.put("name",alarmRuleVOS.get(i).getRuleRemark());
                        // 放入短息模板id
                        jobDataMap.put("contentId",alarmRuleVOS.get(i).getSmsContentId());
                        // 创建JobKey
                        JobKey jobKey = JobKey.jobKey(ruleConfId,"group1");
                        // 创建JobDetail
                        JobDetail jobDetail = JobBuilder.newJob(clazz)
                                .withIdentity(jobKey)
                                //将jobmap保存到JobDetail中
                                .usingJobData(jobDataMap)
                                .build();
                        // 创建Trigger
                        Trigger trigger = TriggerBuilder.newTrigger()
                                .withIdentity(ruleConfId, "group1")
                                .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
                                .build();
                        // 删除原JobDetail ,再放入新的，目的：为了使修改的配置生效
                        scheduler.deleteJob(jobKey);
                        // 再放入
                        scheduler.scheduleJob(jobDetail,trigger);
//                        jobList.add(new AlarmJobBean(jobDetail,trigger));

                    } catch (Exception e) {
                        logger.error("会员新告警调度器任务：{},启动失败，exception is:{}",alarmRuleVOS.get(i).getRuleRemark(),e);
                    }
                }
            }
            // 执行任务
            scheduler.start();
        } catch (Exception e) {
            logger.error("老会员新告警执行失败,原因是:",e);
        }
        logger.info("会员新告警调度器执行END！！！！");
    }
}
